import 'package:flutter/material.dart';
import 'package:ky_tool_plugin/tools/ky_log_utils.dart';
import 'package:ky_tool_plugin/tools/ky_toast.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:dio/dio.dart';
import 'dart:typed_data';
import 'dart:io';
import 'package:system_settings/system_settings.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:ky_tool_plugin/sizefit/ky_int_extension.dart';


class KYPhotoViewWrapper extends StatefulWidget {
  KYPhotoViewWrapper({
    required this.contentStr,
    required this.loadingBuilder,
    required this.backgroundDecoration,
    this.minScale,
    this.maxScale,
    required this.initialIndex,
    required this.galleryItems,
    this.isCanSavePhoto = false,
    this.scrollDirection = Axis.horizontal,
  }) : pageController = PageController(initialPage: initialIndex);

  String contentStr;
  final LoadingBuilder loadingBuilder;
  final Decoration backgroundDecoration;
  final dynamic minScale;
  final dynamic maxScale;
  final int initialIndex;
  final PageController pageController;
  final List galleryItems;
  final bool isCanSavePhoto;
  final Axis scrollDirection;

  @override
  State<StatefulWidget> createState() {
    return _KYPhotoViewWrapperState();
  }
}

class _KYPhotoViewWrapperState extends State<KYPhotoViewWrapper> {
  late int currentIndex;

  @override
  void initState() {
    currentIndex = widget.initialIndex;
    super.initState();
  }

  void onPageChanged(int index) {
    setState(() {
      currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    bool isShowIndex = widget.galleryItems.length>1 ? true:false;
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Container(
        decoration: widget.backgroundDecoration,
        constraints: BoxConstraints.expand(
          height: MediaQuery.of(context).size.height,
        ),
        child: Stack(
          alignment: Alignment.bottomRight,
          children: <Widget>[
//            PhotoView(imageProvider: NetworkImage('url')),
            PhotoViewGallery.builder(
              scrollPhysics: const BouncingScrollPhysics(),
              builder: _buildItem,
              itemCount: widget.galleryItems.length,
              loadingBuilder: widget.loadingBuilder,
              backgroundDecoration: BoxDecoration(
                color: Color.fromRGBO(0, 0, 0, 0),
              ),
              pageController: widget.pageController,
              onPageChanged: onPageChanged,
              scrollDirection: widget.scrollDirection,
            ),

            Positioned(//图片index显示
              top: MediaQuery.of(context).padding.top+15,
              width: MediaQuery.of(context).size.width,
              child: isShowIndex ? Center(
                child: Text("${currentIndex+1}/${widget.galleryItems.length}",style: TextStyle(color: Colors.white,fontSize: 16)),
              ):Container(),
            ),
            Positioned(
              left: 0,
              right: 0,
              bottom: 0,
              child: (widget.contentStr != null && widget.contentStr.length > 0)?Container(
                color: Color.fromRGBO(0, 0, 0, 0.2),
                padding: EdgeInsets.all(15.px),
                child: Text(widget.contentStr,style: TextStyle(color: Colors.white,fontSize: 13),),
              ):Container(),
            ),
            Positioned(//右上角关闭按钮
              right: 10,
              top: MediaQuery.of(context).padding.top,
              child: IconButton(
                icon: Icon(Icons.close,size: 30,color: Colors.white,),
                onPressed: (){
                  Navigator.of(context).pop();
                },
              ),

            ),

            widget.isCanSavePhoto?Positioned(
              bottom: MediaQuery.of(context).padding.bottom +16,
              child: FlatButton(
                child: Text('保存图片',style: TextStyle(color: Colors.white,fontSize: 16),),
                onPressed: (){
                  if (Platform.isIOS){
                    return   _savenNetworkImage();
                  }
                  requestPermission().then((bool){
                    if (bool){
                      _savenNetworkImage();
                    }
                  });

                },
              ),
            ):Container()
          ],
        ),
      ),
    );
  }
  Future<bool> requestPermission() async {
    var status = await Permission.storage.status;
    LogUtils.d('requestPermission======$status');
    if (!status.isGranted) {
      LogUtils.d('isUndeterminedOrisDenied======$status');
      Map<Permission, PermissionStatus> statuses = await [
        Permission.storage,
      ].request();
    }else if (status.isPermanentlyDenied){
      // KYToast.showText('你已拒绝读写手机存储权限，请前往系统设置开启～');
      showDialog(
          barrierDismissible: false,//点击灰色背景的时候是否消失弹出框
          context: context,
          builder: (context){
            return AlertDialog(
              title: Text("温馨提示"),
              content: Text("你当前没有开启读写手机存储权限，是否前往开启？"),
              actions: <Widget>[
                FlatButton(
                  child: Text("取消"),
                  onPressed: (){
                    Navigator.pop(context);//令提示框消失
                  },
                ),
                FlatButton(
                  child: Text("开启"),
                  onPressed: (){
                    //打开的设置
                    SystemSettings.app();
                    Navigator.pop(context);
                  },
                )
              ],
            );
          }
      );

    }
    LogUtils.d('status=====${status.isGranted}');
    return status.isGranted;
  }
  //保存网络图片到本地
  _savenNetworkImage() async {

    var status;
    if (Platform.isIOS){
      status = await Permission.photos.status;
      if (status.isDenied) {
        // We didn't ask for permission yet.
        print('暂无相册权限');
        showDialog(
            barrierDismissible: false,//点击灰色背景的时候是否消失弹出框
            context: context,
            builder: (context){
              return AlertDialog(
                title: Text("温馨提示"),
                content: Text("你当前没有开启相册权限，是否前往开启？"),
                actions: <Widget>[
                  FlatButton(
                    child: Text("取消"),
                    onPressed: (){
                      Navigator.pop(context);//令提示框消失
                    },
                  ),
                  FlatButton(
                    child: Text("开启"),
                    onPressed: (){
                      //打开ios的设置
                      openAppSettings();
                      Navigator.pop(context);
                    },
                  )
                ],
              );
            }
        );


        return;
      }
    }else{
      status = await Permission.storage.status;
    }
    LogUtils.d('nowStatus======${status}');


    KYToast.showLoadingText(loadingText: '正在保存');
    var response = await Dio().get(widget.galleryItems[currentIndex].resource, options: Options(responseType: ResponseType.bytes));
    final result = await ImageGallerySaver.saveImage(Uint8List.fromList(response.data));
    print('saveResult=====$result');
    KYToast.hideHUD();
    if (Platform.isIOS){
      if(result){
        KYToast.showText('保存成功');
      }else{
        KYToast.showText('保存失败');
      }
    }else{
      if(result !=null){
        KYToast.showText('保存成功');

      }else{
        KYToast.showText('保存失败');
      }
    }

  }

  PhotoViewGalleryPageOptions _buildItem(BuildContext context, int index) {
    final GalleryExampleItem item = widget.galleryItems[index];
    return PhotoViewGalleryPageOptions(
      onTapUp: (BuildContext context, TapUpDetails details, PhotoViewControllerValue controllerValue){
        Navigator.of(context).pop();
      },
      imageProvider:CachedNetworkImageProvider(item.resource),
//      initialScale: PhotoViewComputedScale.contained,
//      minScale: PhotoViewComputedScale.contained * (0.5 + index / 10),
//      maxScale: PhotoViewComputedScale.covered * 1.1,

      heroAttributes: PhotoViewHeroAttributes(tag: item.id),
    );
  }
}

//Hero 动画组件
class GalleryExampleItemThumbnail extends StatelessWidget {
  const GalleryExampleItemThumbnail(
      {required Key key, required this.galleryExampleItem, required this.onTap})
      : super(key: key);

  final GalleryExampleItem galleryExampleItem;

  final GestureTapCallback onTap;

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(4),
      ),
      child: GestureDetector(
        onTap: onTap,
        child: Hero(
          tag: galleryExampleItem.id,
          child: CachedNetworkImage(imageUrl: galleryExampleItem.resource,fit: BoxFit.cover,),
          // child:Image.network(galleryExampleItem.resource,fit: BoxFit.cover,),
        ),
      ),
    );
  }
}
//model
class GalleryExampleItem {
  GalleryExampleItem({required this.id, required this.resource, this.isSvg = false});
  //hero的id 不能重复
  String id;
  String resource;
  bool isSvg;
}
